import requests
from lxml import etree
import time

def get_ip_real_address(ipstr):
    """
    获取IP地址的真实物理位置
    
    Args:
        ipstr (str): IP地址字符串
        
    Returns:
        str: IP地址的物理位置信息
    """
    try:
        # 构建请求URL
        url = f"https://ip.cn/ip/{ipstr}.html"
        
        # 设置请求头，模拟浏览器访问
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
        }
        
        # 发送GET请求
        response = requests.get(url, headers=headers, timeout=10)
        
        # 检查响应状态
        if response.status_code != 200:
            return f"请求失败，状态码: {response.status_code}"
        
        # 解析HTML内容
        html = etree.HTML(response.text)
        
        # 使用XPath提取位置信息
        location_elements = html.xpath('//div[@class="module mod-panel"]//table/tbody/tr[2]/td[1]/span')
        
        if not location_elements:
            return "未找到位置信息"
        
        # 返回位置信息文本
        return location_elements[0].text.strip()
        
    except Exception as e:
        return f"获取IP位置信息时出错: {str(e)}"

if __name__ == "__main__":
    # 测试函数
    test_ips = ["180.101.245.251", "119.136.146.236"]
    
    print("IP地址真实位置查询测试:")
    print("-" * 40)
    
    for ip in test_ips:
        print(f"IP: {ip}")
        location = get_ip_real_address(ip)
        print(f"位置: {location}")
        print("-" * 40)
        # 添加延时，避免频繁请求
        time.sleep(1)